//
//  ViewController.m
//  IPDirectConnection
//
//  Created by lianglibao on 2019/4/20.
//  Copyright © 2019 lianglibao. All rights reserved.
//

#import "ViewController.h"
#import "NetworkService/NetWorkManager.h"
#import "WkWebViewViewController.h"
#import "NetWorkRequestSerializer.h"
#import "UIView+ATFrame.h"

#import "FetchIPAdressManager.h"

@interface ViewController ()
@property (nonatomic, strong) UIButton *btn1;
@property (nonatomic, strong) UIButton *btn2;
@property (nonatomic, strong) UIButton *btn3;
@property (nonatomic, strong) UIButton *btn4;
@property (nonatomic, strong) UITextView *logTextView;
@end

@implementation ViewController
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSStringFromClass(self.class);
    
	[self setupSubviews];
	
    //[self testPrintConslogToTextView];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.logTextView.size = CGSizeMake(self.view.width, self.view.height - self.btn1.bottom - 20);
    self.logTextView.origin = CGPointMake(0, self.btn1.bottom+20);
}

/**
 将当前即时log打印输出到UITextView里
 */
- (void)testPrintConslogToTextView {
    // 注册STDOUT_FILENO类型 文件描述符 log输出通知.
    [self redirectSTD:STDERR_FILENO];
}

- (void)setupSubviews {
    [self.view addSubview:({
        UIButton *tempBtn = UIButton.alloc.init;
		self.btn1 = tempBtn;
        [tempBtn setTitle:@"游客登录" forState:UIControlStateNormal];
        [tempBtn sizeToFit];
		tempBtn.backgroundColor = [UIColor blackColor];
        tempBtn.origin = CGPointMake(20, self.navigationController.navigationBar.bottom + 100);
        [tempBtn addTarget:self action:@selector(login)forControlEvents:UIControlEventTouchUpInside];
        tempBtn;
    })];
    
    [self.view addSubview:({
        UIButton *btn = UIButton.alloc.init;
		self.btn2 = btn;
        [btn setTitle:@"打开WebView" forState:UIControlStateNormal];
        btn.backgroundColor = [UIColor blackColor];
        [btn sizeToFit];
        btn.origin = CGPointMake(self.btn1.right + 20, self.navigationController.navigationBar.bottom + 100);
        [btn addTarget:self action:@selector(openWebview) forControlEvents:UIControlEventTouchUpInside];
        btn;
    })];
	
	[self.view addSubview:({
		UIButton *btn = UIButton.alloc.init;
		self.btn3 = btn;
        [btn setTitle:@"清空" forState:UIControlStateNormal];
        [btn sizeToFit];
		btn.backgroundColor = [UIColor blackColor];
        btn.origin = CGPointMake(self.btn2.right + 20, self.navigationController.navigationBar.bottom + 100);
        [btn addTarget:self action:@selector(clearTextview) forControlEvents:UIControlEventTouchUpInside];
		btn;
	})];

    
    [self.view addSubview:({
        UITextView *logTextView = [[UITextView alloc] init];
        self.logTextView = logTextView;
        logTextView.editable = NO;
        logTextView;
    })];
}


// 通知方法
- (void)redirectNotificationHandle:(NSNotification *)nf {
    // 设置在后台读取
    [[nf object] readInBackgroundAndNotify];
    NSData *data = [[nf userInfo] objectForKey:NSFileHandleNotificationDataItem];
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    // logTextView 就是要将日志输出的视图（UITextView）
    self.logTextView.text = [NSString stringWithFormat:@"%@\n\n%@",self.logTextView.text, str];
}

- (void)redirectSTD:(int)fd {
    // 初始化一个NSPipe 对象
    NSPipe * pipe = [NSPipe pipe] ;
    NSFileHandle *pipeReadHandle = [pipe fileHandleForReading];
    dup2([[pipe fileHandleForWriting] fileDescriptor], fd) ;
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(redirectNotificationHandle:)
                                                 name:NSFileHandleReadCompletionNotification
                                               object:pipeReadHandle]; // 注册通知
    [pipeReadHandle readInBackgroundAndNotify];
}

- (void)login {
    NetWorkManager *mgr = [NetWorkManager shareInstance];
    NSString *uuid = AppMetaModel.UUIDString ;
    
    [mgr NetGET:@"https://www.sina.com.cn" parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *str = nil;
        if ([responseObject isKindOfClass:NSData.class]) {
            str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        } else {
            str = responseObject;
        }

        NSLog(@"+++成功!+++\n%@", str);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"!!!失败!!!\n%@", error);
    }];

}

- (void)openWebview {
    WkWebViewViewController *webVC = [[WkWebViewViewController alloc] init];
    [self.navigationController pushViewController:webVC animated:YES];
}

- (void)clearTextview {
	self.logTextView.text = nil;
}

@end
